package com.itheima.myiotest2;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        //1.定义变量，表示初始文件路径，文件中存储所有的学生信息
        String src = "myiotest\\test.txt";
        //2.定义变量，表示备份文件，一开始文件为空
        String backups = "myiotest\\backups.txt";

        //先把文件内容获取出来放入集合
        ArrayList<String> list = getStrings(src);
        //System.out.println(list);

        //判断
        if (list.size()==0){
            //如果集合为空，说明所有学生都点完了，从备份文件中获取数据到原本文件
//            FileUtil.copy(backups,src,true);
            list = getStrings(backups);
            //重新写回本地文件
            fw(src,list,false);
            //删除备份文件
            new File(backups).delete();
        }

        //随即名字
        Collections.shuffle(list);
        String s = list.get(0);
        System.out.println(s);
        //随机到的不能再随机到了，把随机到的删除和放入备用文件
        list.remove(s);
//        FileUtil.writeString(s, backups, Charset.defaultCharset());
        fw(backups, s,true);
        //再去覆盖原始文件
//        FileUtil.writeLines(list,src, Charset.forName("utf-8"));
        fw(src, list,false);

    }

    private static void fw(String backups, ArrayList<String> list,boolean isOpen) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(backups,isOpen));
        for (String s : list) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
    }

    private static void fw(String backups, String s,boolean isOpen) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(backups,isOpen));
        bw.write(s);
        bw.newLine();
        bw.close();
    }

    private static ArrayList<String> getStrings(String src) throws IOException {
        ArrayList<String> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(src));
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        return list;
    }
}
